global  class PurchaseDemandPlanController {

	public String msg {get;private set;}

	public Boolean isSuccess {get; private set;}

	public Boolean isErr {get; private set;}

	public String dataJson {get; private set;}

	public String saveJson {get; set;}

	public String backId {get; private set;}

    public Boolean isSum {get; private set;}// 是否为汇总数据 
    public Boolean isConfirmed {get; private set;}// 是否为确认

    public String currentMonth {get;private set;}
    public String company {get;private set;}
    public String companyName {get;private set;}


    public Integer status  {get; private set;}
    public Boolean isApproval  {get;private set;}



    public Boolean isPass  {get;private set;}
    public Boolean isSync  {get;private set;}



    public String province {get;private set;}
    public String cate {get;private set;}



    private PurchaseDemandPlan__c pdp ;

    private boolean isNew ;

	public PurchaseDemandPlanController(ApexPages.StandardController con){

         preInit();
    }

    public PurchaseDemandPlanController() {
        
        preInit();

    }
    private void preInit(){
        isSync = System.currentPageReference().getParameters().get('isSync') != null ;

        backId = System.currentPageReference().getParameters().get('id');
        pdp = new PurchaseDemandPlan__c();
        isNew = backId == null;
        isApproval = false;
        isPass = false;
        status = 0;
    }



    public void init(){
         
    	try {


    		//if(String.isBlank(backId))throw new DmlException('页面打开错误!');
            setNil();

            Boolean isThird = false;
           if(!isNew) {

                pdp = [select Id ,OwnerId ,Name ,IsThird__c ,Company__c,ProductOwner__c,Status__c,Category__c,IsSycToNc__c,SyncResult__c,Year__c,Month__c,Province__c from PurchaseDemandPlan__c where Id=:backId ];
                if(isSync )return;

                if(pdp.Status__c == '审批中(子公司负责人待确认)' && pdp.ProductOwner__c != UserInfo.getUserId() ) throw new DmlException('没有权限!');
                if(pdp.Status__c == '审批中(子公司负责人已确认)' && pdp.OwnerId != UserInfo.getUserId() ) throw new DmlException('没有权限!');

                
                 status =  pdp.Status__c == '审批中(子公司负责人待确认)' ?  1 : (pdp.Status__c == '审批中(子公司负责人已确认)' ? 2 : (pdp.Status__c =='审批中(采购专员已修订)' ? 3 : (pdp.Status__c == '已批准' ? 4 : 0)));


                province = pdp.Province__c;
                cate = pdp.Category__c;

                isApproval =status > 0  ;

                isPass = status >=3 ;
    		    getDetails();

                isThird = pdp.IsThird__c ; 


            }else{
                 Map<String,String> companyMap = ImportObject.getPicklistValues('PurchaseDemandPlan__c', 'Company__c', false);
                User u = [select Id,UserRole.Name ,SubCompany__c from User where Id =:UserInfo.getUserId()];

                pdp.Company__c = companyMap.get(u.SubCompany__c);
                pdp.Year__c = System.today().year()+'年';
                pdp.Month__c = System.today().month() +'月';

                isThird = u.UserRole != null &&  u.UserRole.Name.contains('三方') ; 


            }
    	    initYM();
            Map<String,String> companyNameMap  = ImportObject.getPicklistValues('PurchaseDemandPlan__c', 'Company__c', true);
            companyName = companyNameMap.get(company);
            if(isThird){
                company = 'SFYW';
                companyName = '三方业务';
            }


    	}catch (Exception e) {
    	    
    	    isErr = true;
    	    ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    	  //  ApexPages.addMessage(new ApexPages.Message )


    	}
    	
    }

    private void initYM(){
        company = pdp.Company__c ;
        //if( String.isBlank(pdp.Company__c ) ) throw new DmlException('自产采购需求计划公司不能为空!');
        if(String.isBlank(pdp.Year__c ) || String.isBlank(pdp.Month__c ) ) throw new DmlException('自产采购需求计划年度和月份不能为空!');
        Integer m = Integer.ValueOf(pdp.Month__c.replace('月',''));
        currentMonth = pdp.Year__c.replace('年','')+ (m < 10 ?( '0'+m ): m +'');


    }

    public void setNil(){

    	dataJson = '[]';
    	saveJson = '[]';
    }

    public void getDetails(){

    	List<String>fields = new List<String>(getFields());

    	String sql = 'select '+ String.join(fields, ',') +',Product__r.Notice__c,Product__r.ProductName__c ,Product__r.NCCode__c,Product__r.SerialNo__c,Product__r.Spec__c,Product__r.Unit__c,Product__r.TypeName__c,Product__r.Category1__c,Product__r.Model__c,Product__r.sealflag__c,Product__r.NCinvshortname__c '
    	+ ',PurchaseDemandPlan__r.Category__c,PurchaseDemandPlan__r.Company__c,PurchaseDemandPlan__r.Province__c from PurchaseDemandPlanDetail__c  where PurchaseDemandPlan__c =\''+backId+'\'';
    	List<PurchaseDemandPlanDetail__c> pls = Database.query(sql);

    	List<Object> tmp = new List<Object>();
    	for (PurchaseDemandPlanDetail__c p:pls ) {
    		
    		tmp.add(new PurchaseBean(p));

    	}

    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }
    public void save(){
    	msg = '';

    	//解析数据 
        Map<String,Object> saveMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

        pdp.Province__c = (String)saveMap.get('province');
        pdp.Category__c = (String)saveMap.get('cate');
        if(status == 1 )pdp.Comfirm__c = '子公司确认';
        if(status == 2 )pdp.Comfirm__c = '采购确认';

    	List<Object> saveList = (List<Object>) saveMap.get('data');
    	
    	List<PurchaseDemandPlanDetail__c> pLs = new List<PurchaseDemandPlanDetail__c>();
        Map<String,Id> productMap = new Map<String,Id>();
        Set<Id> exset = new Set<Id>();
    	for (Object o  : saveList) {
    		
    		Map<String,Object> mo = (Map<String,Object>) o;
    		PurchaseDemandPlanDetail__c p = new PurchaseDemandPlanDetail__c();
    		//p.put();
    		p.Id = DataUtil.getStringValue(mo.get('Id'));
    		p.NCcode__c = DataUtil.getStringValue(mo.get('INVCODE'));
    		p.BudgetCate__c = DataUtil.getStringValue(mo.get('CATE'));

            P.NumberOfCustomers3__c = DataUtil.getDecimalValue(mo.get('A3'));
            P.NumberOfCustomers6__c = DataUtil.getDecimalValue(mo.get('A6'));
            P.Differences6__c = DataUtil.getDecimalValue(mo.get('DIF6'));

            p.GrossDemand1__c  = DataUtil.getDecimalValue(mo.get('PLAN1'));
            p.GrossDemand2__c  = DataUtil.getDecimalValue(mo.get('PLAN2'));
            p.GrossDemand3__c  = DataUtil.getDecimalValue(mo.get('PLAN3'));
            
            p.ReservedQuantity1__c =  DataUtil.getDecimalValue(mo.get('ENSURE1'));
            p.ReservedQuantity2__c =  DataUtil.getDecimalValue(mo.get('ENSURE2'));
            p.ReservedQuantity3__c=  DataUtil.getDecimalValue(mo.get('ENSURE3'));

            p.NewQuantity1__c =  DataUtil.getDecimalValue(mo.get('NEW1'));
            p.NewQuantity2__c =  DataUtil.getDecimalValue(mo.get('NEW2'));
            p.NewQuantity3__c=  DataUtil.getDecimalValue(mo.get('NEW3'));

            p.ForecastValue1__c =  DataUtil.getDecimalValue(mo.get('PRE1'));
            p.ForecastValue2__c =  DataUtil.getDecimalValue(mo.get('PRE2'));
            p.ForecastValue3__c =  DataUtil.getDecimalValue(mo.get('PRE3'));


            p.NetDemandAmend1__c = DataUtil.getDecimalValue(mo.get('DEM1')); 
            p.NetDemandAmend2__c = DataUtil.getDecimalValue(mo.get('DEM2'));
            p.NetDemandAmend3__c = DataUtil.getDecimalValue(mo.get('DEM3'));

            p.SpecialDemd1__c = DataUtil.getDecimalValue(mo.get('SD1')); 
            p.SpecialDemd2__c = DataUtil.getDecimalValue(mo.get('SD2'));
            p.SpecialDemd3__c = DataUtil.getDecimalValue(mo.get('SD3'));    
            

            p.AverageDeliveryIn6__c =  DataUtil.getDecimalValue(mo.get('OA6'));
            p.AverageDeliveryIn3__c =  DataUtil.getDecimalValue(mo.get('OA3'));
            p.Stdev__c =  DataUtil.getDecimalValue(mo.get('STDEV'));

            p.SafetyStock__c =  DataUtil.getDecimalValue(mo.get('SFNUM'));
            p.Volatility__c =  DataUtil.getDecimalValue(mo.get('SFRITO'));




            if(p.NCcode__c != null )productMap.put(p.NCcode__c, null);
    		pLs.add(p);
            if(p.Id != null )exset.add(p.Id );

    	}

        for (Product__c p  :[select Id,NCCode__c from Product__c where NCCode__c in:productMap.keySet() and RecordType.DeveloperName = 'NCProduct'] ) {
            productMap.put(p.NCCode__c, p.Id);
        }


    	SavePoint sp = Database.setSavepoint();
    	try {

            upsert pdp ; 
            delete [select Id from  PurchaseDemandPlanDetail__c where PurchaseDemandPlan__c =:pdp.Id and Id not in: exset];
            for (PurchaseDemandPlanDetail__c p  : pLs) {
                p.Product__c = productMap.get(p.NCcode__c);
                if(p.Id == null )  p.PurchaseDemandPlan__c = pdp.Id ;
            }
    		upsert  pLs;
            backId = pdp.Id ;
    		isSuccess = true;
    		msg = '保存成功!';
    	    
    	}
    	catch (Exception e) {
            if(isNew)pdp.Id = null;
    	    Database.rollback(sp);
    	    msg = '保存失败:'+e.getMessage();
    	}
    	


    }

    public Set<String> getFields(){

    	Schema.DescribeSobjectResult m = PurchaseDemandPlanDetail__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        Set<String> fields  = new Set<String>();
        for (String field : fieldMap.keySet()) {
             Schema.SObjectField sf  = fieldMap.get(field);
            	fields.add(sf.getDescribe().getLocalName());
             //fbeanMap.put(sf.getDescribe().getLocalName(),sf.getDescribe().getType()+''); 
             
	    }
        return fields;
    }


    //同步请购单到NC 
    public  void  sync() {
       
        try{

            if(pdp.Status__c  != '已批准')throw new DmlException( '没有审批成功,不能同步!');
            if(pdp.IsSycToNc__c ==true ) throw new DmlException( '已经同步,不要重复点击!');
            
            User u = [select Id, ExuserCode__c from User where Id =:UserInfo.getUserId()];


            Map<String,String> headMap = new Map<String,String>();
            headMap.put('caccountyear',String.valueOf(System.now().year()));
            headMap.put('pk_corp',pdp.Company__c);
            headMap.put('coperator',u.ExuserCode__c);
            headMap.put('dpraydate',System.now().format('yyyy-MM-dd'));
            headMap.put('vmemo',pdp.Name );
           // headMap.put('vdef19',eprp.Equipment__r.ProductName__c );
            //headMap.put('vdef20',eprp.Id );



            List<PurchaseDemandPlanDetail__c> eprdList  = [select Id,NCcode__c,NetDemandAmend1__c
            from PurchaseDemandPlanDetail__c where PurchaseDemandPlan__c =: pdp.Id  ];
            if(eprdList.size() == 0)throw new DmlException('没有数据!');
            ///分单
            List<Map<String,String>> bodyList = new List<Map<String,String>>();
            Integer i = 0;
            for (PurchaseDemandPlanDetail__c eprd : eprdList) {
                i ++ ;

                if(eprd.NetDemandAmend1__c == null ) continue;

                Map<String,String> body = new Map<String,String>();
                body.put('rowno', String.valueOf(i));
                body.put( 'cmangid',eprd.NCcode__c);//存货编码
                body.put('npraynum',String.valueOf(eprd.NetDemandAmend1__c));//订货量
                body.put('ddemanddate',System.now().format('yyyy-MM-dd') );
                body.put('pk_corp',pdp.Company__c);//公司编码
                body.put('pk_reqcorp',pdp.Company__c );//公司编码
                body.put('pk_purcorp',pdp.Company__c );//公司编码 
               // body.put('cwarehouseid',eprp.DemandWarehouse__c );//仓库

                bodyList.add(body);

            }
            if(bodyList.isEmpty() )throw new DmlException('没有需要同步的数据!');

            //组装XML 
            String xml = '<ufinterface roottag="bill" billtype="20" replace="Y" receiver="web" sender="20" isexchange="Y"  proc="add" operation="req">';
            xml += '<bill id="'+pdp.Id+'" subdoctype="">';
            //组装表头
            xml+='<billhead>';
            for (String k : headMap.keySet()) {
                xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
            }
            xml+='</billhead>';

            //组装表体
            xml+='<billbody>';
            for (Map<String,String> row : bodyList) {
                xml+='<entry>';
                for (String k : row.keySet()) {
                    xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
                }
                xml+='</entry>';

            }
            xml+='</billbody>';

            xml +='</bill></ufinterface>';

            System.debug(xml);

            String postURL = Label.queryNCPreOrder;
           //测试环境地址: 
           // postURL = 'https://esb.maccura.com:9088/api/Domain/even1/ncstock/data';
            ///发送请求
            String data = EncodingUtil.urlEncode(xml,'UTF-8');
            //生成POST请求
            HttpRequest req = new HttpRequest(); 
            // String accountn = 'CS180824' ; // 正式'01'
             String accountn = Label.NCAccount ; // 正式'01'
            req.setBody('data=' + data+'&account='+accountn+'&receiver='+pdp.Company__c);
            req.setEndpoint(postURL); 
            System.debug(req.getBody());
            //POST数据到微信接口，设置编码为GB2312,防止乱码
            req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
            req.setMethod('POST'); 
            //发送数据并取得返回结果
            HttpResponse res = Utils.postRequest(req,1); 
            //设置编码为GB2312，防止读取数据时乱码
            res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
            String result = res.getBody();
            System.debug('*** : ' + result);
            if (res.getStatusCode() == 200) {


                 Map<String,Object> r =null;
                     //如果是测试
                    if(Test.isRunningTest()){
                      Map<String,Object>  resBody= new Map<String,Object>();
                      resBody.put('code','0');
                      /*
                    {"result":"[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]","code":"0","msg":"success"}
                      */
                      resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                        r =  resBody;
                    }else{
                      r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                    }

                 if(r.get('code') == 0|| r.get('code')=='0' ){
                    List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
                        Map<String,Object> rs = (   Map<String,Object>)rList[0];
                        if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
                           /* for (SameBatchNumber__c sd: sdList) {
                               
                            }*/
                            String resJso = JSON.serialize(rs);
                            pdp.SyncResult__c = resJso.length() > 255 ? resJso.substring(0, 254) : resJso;
                            pdp.IsSycToNc__c = true;
                            update pdp;
                            //Approval.lock(sn);
                            msg =  '同步成功!';
                        }else{
                            throw new DmlException( String.valueOf(rs.get('resultdescription')));
                        }

                 }else{

                   throw new DmlException('接口异常,请联系系统管理员!');
                 }



            }else{

                throw new DmlException( '接口异常,请联系系统管理员!');
            }

        }catch(Exception e ){
            msg = e.getMessage();
        }
        





    }

    public class PurchaseBean{
        public String Id ;
        public String INVCODE;
        public String INVNAME;
        public String INVSPEC;
        public String CATE;

        public Decimal A3;
        public Decimal A6;
        public Decimal DIF6;

        public Decimal PLAN1;
        public Decimal PLAN2;
        public Decimal PLAN3;


        public Decimal ENSURE1;
        public Decimal ENSURE2;
        public Decimal ENSURE3;

        public Decimal NEW1;
        public Decimal NEW2;
        public Decimal NEW3;


        public Decimal OA6;
        public Decimal OA3;
        //月均出库量<br/>标准差
        public Decimal STDEV;
        public Decimal SFNUM;
        //月均出库<br/>波动率
        public Decimal SFRITO;

        public Decimal PRE1;
        public Decimal PRE2;
        public Decimal PRE3;

        public Decimal DEM1;
        public Decimal DEM2;
        public Decimal DEM3;

        public Decimal SD1;
        public Decimal SD2;
        public Decimal SD3;


        public PurchaseBean (PurchaseDemandPlanDetail__c p ){
            Id = p.Id;

            INVCODE = p.NCcode__c;
            INVNAME = p.Product__r.ProductName__c ;
            INVSPEC = p.Product__r.Spec__c;
            CATE = p.BudgetCate__c;

            A3 = p.NumberOfCustomers3__c;
            A6= p.NumberOfCustomers6__c;
            DIF6= p.Differences6__c;

            PLAN1 = p.GrossDemand1__c;
            PLAN2 = p.GrossDemand2__c;
            PLAN3 = p.GrossDemand3__c;

            ENSURE1 = p.ReservedQuantity1__c;
            ENSURE2 = p.ReservedQuantity2__c;
            ENSURE3 = p.ReservedQuantity3__c;

            NEW1 = p.NewQuantity1__c;
            NEW2 = p.NewQuantity2__c;
            NEW3 = p.NewQuantity3__c;

            OA6 = p.AverageDeliveryIn6__c;
            OA3 = p.AverageDeliveryIn3__c;
            STDEV = p.Stdev__c;
            SFNUM = p.SafetyStock__c;
            SFRITO = p.Volatility__c;


            PRE1 = p.ForecastValue1__c;
            PRE2 = p.ForecastValue2__c;
            PRE3 = p.ForecastValue3__c;

            DEM1 = p.NetDemandAmend1__c;
            DEM2 = p.NetDemandAmend2__c;
            DEM3 = p.NetDemandAmend3__c;

            SD1 = p.SpecialDemd1__c;
            SD2 = p.SpecialDemd2__c;
            SD3 = p.SpecialDemd3__c;


        }

        


    }





}